//
//  WH_MyinfoViewController.m
//  App_6.23
//
//  Created by wanghao on 16/7/18.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_MyinfoViewController.h"
#import "WH_Home.h"
#import "WH_AddressViewController.h"
#import "WH_MyeditViewController.h"

@interface WH_MyinfoViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *myDataArr;
@property (nonatomic, strong) UIImageView *imageTitle;
@property (nonatomic, strong) UILabel *datalabel;
@property (nonatomic, strong) NSMutableArray *detailLabelArr;
@property (nonatomic, copy) NSString *nickStr;
@end

@implementation WH_MyinfoViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.detailLabelArr removeAllObjects];
    [self postData];
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.myDataArr = [NSMutableArray arrayWithObjects:@"头像", @"ID", @"账号", @"昵称", @"余额", @"地址管理", nil];
    
    [self createMyTable];
    [self postData];
    [self createImageView];
}

- (void)createMyTable{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 60;
    //[self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MyCell"];
    [self.view addSubview:self.myTableView];
    self.myTableView.scrollEnabled = NO;
    self.myTableView.tableFooterView = [UIView new];
    
}
-(void)postData{
    
    NSString *body = [NSString stringWithFormat:@"action=account&user_id=%@",NSUSERID];
    
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSDictionary *user_array = [dic objectForKey:@"user_array"];
        WH_Home *mine = [WH_Home modelWithDictionary:user_array];
        NSString *nameStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        if (nameStr.length == 0) {
            
            nameStr = @"loading...";
        }
        self.detailLabelArr = [NSMutableArray arrayWithObjects:@"", NSUSERID, nameStr, mine.user_nick, mine.user_price, @"", nil];
        _nickStr = mine.user_nick;
        [self.myTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.myDataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    static NSString *mycell = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mycell];
    if (cell == nil){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:mycell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = self.myDataArr[indexPath.row];
    cell.detailTextLabel.text = self.detailLabelArr[indexPath.row];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    if (indexPath.row == 0 || indexPath.row == 3 || indexPath.row == 5) {
        if (indexPath.row == 0) {
            
            cell.accessoryView = self.imageTitle;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
    
}

-(void)createImageView{
    
    //用户头像图
    self.imageTitle = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.imageTitle.layer.cornerRadius = 50 / 2.f;
    self.imageTitle.layer.borderWidth = 2;
    self.imageTitle.layer.borderColor = [UIColor whiteColor].CGColor;
    self.imageTitle.clipsToBounds = YES;
    self.imageTitle.userInteractionEnabled = YES;
    [self.imageTitle sd_setImageWithURL:[NSURL URLWithString:_userAvatar] placeholderImage:PLACEHOLDER_CELL_SAME];

    //添加tap
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectImageAlert)];
    [self.imageTitle addGestureRecognizer:tap];

}

- (void)selectImageAlert {
    UIAlertController *alert = [[UIAlertController alloc] init];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImagePicker:UIImagePickerControllerSourceTypeCamera];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)selectImagePicker:(UIImagePickerControllerSourceType) type {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = type;
    picker.delegate = self;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES
                     completion:nil];
    
}
#pragma mark - post头像

// 回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *img = info[UIImagePickerControllerEditedImage];
    self.imageTitle.image = img;
    [picker dismissViewControllerAnimated:YES completion:^{
        
        [self sendImg:img];
    }];
}
- (void)sendImg:(UIImage *)sender {
    
    NSData *data = UIImageJPEGRepresentation(sender, 0.8);
    NSString *image64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSString *imageStr = [NSString stringWithFormat:@"jpg;base64,%@",image64];
    
    NSMutableArray *imageUrl = [NSMutableArray arrayWithObjects:imageStr, nil];
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"share_upload_img" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:imageUrl forKey:@"file_data"];
    
    NSMutableArray *urlArray = [NSMutableArray array];
    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        NSArray *imgArr = [dic objectForKey:@"img_array"];

        if ([status isEqualToString:@"success"]) {
            for (NSDictionary *dic in imgArr) {
                
                NSString *url = [dic objectForKey:@"url"];
                [urlArray addObject:url];
            }
            NSLog(@"urlArray====%ld",urlArray.count);
            [self postAvatar:urlArray];
            [WSProgressHUD showImage:nil status:status maskType:WSProgressHUDMaskTypeClear];
        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }
        
        
    } failure:^(NSError *error) {
        
        
    }];

}
-(void)postAvatar:(NSMutableArray *)urlArr{
    
    NSLog(@"urlArr===%ld",urlArr.count);
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"account_edit" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:@"Male" forKey:@"user_gender"];
    [para setObject:urlArr forKey:@"user_avatar"];
    [para setObject:_nickStr forKey:@"user_nick"];

    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        //NSDictionary *dic = result;
        //NSString *status = [dic objectForKey:@"status"];
        //NSString *message = [dic objectForKey:@"message"];
        
        
    } failure:^(NSError *error) {
        
        
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 5) {
        
        WH_AddressViewController *addressVC = [[WH_AddressViewController alloc] init];
        
        [self.navigationController pushViewController:addressVC animated:YES];
    }else if (indexPath.row == 3){
        
        WH_MyeditViewController *myeditVC = [[WH_MyeditViewController alloc] init];
        myeditVC.nickStr = self.detailLabelArr[indexPath.row];
        [self.navigationController pushViewController:myeditVC animated:YES];
    }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
